package com.ylfstu.jdbc.JdbcUtils;

import org.junit.jupiter.api.Test;

import java.sql.*;

/**
 * @Author: Joy_yang
 * @Date: 2022/10/19 22:46
 * 使用jdbc工具类，完成dml 和 select
 */
public class JdbcUtils_Use {
    @Test
    public void testSelect() {
        //1. 得到连接
        Connection connection = null;
        //2. 执行SQL
        String sql = "select * from actor ";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String sex = resultSet.getString("sex");
                Date date = resultSet.getDate("borndate");
                String phone = resultSet.getString("phone");
                System.out.println(id + "\t" + name + "\t" + sex + "\t" + date + "\t" + phone);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JdbcUtils.close(resultSet, preparedStatement, connection);
        }
    }

    @Test
    public void testDML() { //insert, update, delete
        //1. 得到连接
        Connection connection = null;
        //2. 执行SQL
        String sql = "update actor set name = ? where id = ? ";
        PreparedStatement preparedStatement = null;
        try {
            connection = JdbcUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "周星驰");
            preparedStatement.setInt(2, 3);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JdbcUtils.close(null, preparedStatement, connection);
        }


    }
}







